package org.dromara.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.constant.MachineConstant;
import org.dromara.system.converter.MachineConverters;
import org.dromara.system.domain.SimUserLevel;
import org.dromara.system.domain.bo.SimUserLevelBo;
import org.dromara.system.domain.bo.VariableLevelBo;
import org.dromara.system.domain.vo.SimUserLevelVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SimUserLevelMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISimUserLevelService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户等级Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SimUserLevelServiceImpl extends ServiceImpl<SimUserLevelMapper, SimUserLevel>
    implements ISimUserLevelService {

    private final SysUserMapper sysUserMapper;

    /**
     * 查询用户等级
     *
     * @param id 主键
     * @return 用户等级
     */
    @Override
    public SimUserLevelVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户等级列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户等级分页列表
     */
    @Override
    public TableDataInfo<SimUserLevelVo> queryPageList(SimUserLevelBo bo, PageQuery pageQuery) {
        IPage<SimUserLevelVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SimUserLevelVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);

    }

    /**
     * 查询符合条件的用户等级列表
     *
     * @param bo 查询条件
     * @return 用户等级列表
     */
    @Override
    public List<SimUserLevelVo> queryList(SimUserLevelBo bo) {
        LambdaQueryWrapper<SimUserLevel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SimUserLevel> buildQueryWrapper(SimUserLevelBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SimUserLevel> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SimUserLevel::getId);
        lqw.eq(bo.getUserId() != null, SimUserLevel::getUserId, bo.getUserId());
        lqw.eq(bo.getLevelNumber() != null, SimUserLevel::getLevelNumber, bo.getLevelNumber());
        lqw.like(StringUtils.isNotBlank(bo.getLevelName()), SimUserLevel::getLevelName, bo.getLevelName());
        lqw.eq(bo.getLevelRate() != null, SimUserLevel::getLevelRate, bo.getLevelRate());
        return lqw;
    }

    /**
     * 新增用户等级
     *
     * @param bo 用户等级
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SimUserLevelBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        SimUserLevel add = MapstructUtils.convert(bo, SimUserLevel.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户等级
     *
     * @param bo 用户等级
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SimUserLevelBo bo) {
        SimUserLevel update = MapstructUtils.convert(bo, SimUserLevel.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SimUserLevel entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户等级信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


    @Override
    public List<SimUserLevelVo> queryVariableLevel(VariableLevelBo bo) {
        Long userId = LoginHelper.getUserId();
        SysUserVo sysUserVo = sysUserMapper.selectVoById(bo.getUserId());
        BusinessException.isTrue(!ObjectUtil.equal(sysUserVo.getPId(), userId), "必须由直属代理修改等级！");
        SysUserVo currentUser = sysUserMapper.selectVoById(userId);
        List<SimUserLevel> list = Lists.newArrayList();
        if (ObjectUtil.equal(currentUser.getUserId(), MachineConstant.ADMIN)) {
            list = lambdaQuery().orderByDesc(SimUserLevel::getLevelNumber).list();
        } else {
            list = lambdaQuery()
                .le(SimUserLevel::getLevelNumber, currentUser.getLevel())
                .orderByDesc(SimUserLevel::getLevelNumber).list();
        }
        return MachineConverters.INSTANCE.toSimUserLevelVoList(list);
    }
}
